package com.example.a2209_shop.fgViewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.BannerEntityResult
import com.example.base.entity.CarEntity
import com.example.base.entity.CateEntityResult
import com.example.base.entity.GoodsEntityResult
import com.example.base.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class HomeViewmodel:BaseViewModel() {

    val bannerSuccess = MutableLiveData<BannerEntityResult>()
    val bannerFail = MutableLiveData<String>()

    fun banner(){
        viewModelScope.launch {
            try {
               bannerSuccess.value = apiServer.banner()
            }catch (e:Exception){
                bannerFail.value = e.message
            }
        }
    }

    val cateSuccess = MutableLiveData<CateEntityResult>()
    val cateFail = MutableLiveData<String>()

    fun cate(){
        viewModelScope.launch {
            try {
                cateSuccess.value = apiServer.cate()
            }catch (e:Exception){
                cateFail.value = e.message
            }
        }
    }

    val goodsSuccess = MutableLiveData<GoodsEntityResult>()
    val goodsFail = MutableLiveData<String>()

    fun goods(category_id :Int,currentPage :Int,pageSize :Int){
        viewModelScope.launch {
            try {
                goodsSuccess.value = apiServer.goods(category_id, currentPage, pageSize)
            }catch (e:Exception){
                goodsFail.value = e.message
            }
        }
    }

    val addSuccess = MutableLiveData<CarEntity>()
    val addFail = MutableLiveData<String>()

    fun addCar(count:Int,goods_id:Int){
        viewModelScope.launch {
            try {
                Log.d("ssss", "addCar: dcfvgbhnj")
                val map = mutableMapOf<String,Int>()
                map["count"] = count
                map["goods_id"] = goods_id
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                addSuccess.value = apiServer.addCar(body)

            }catch (e:Exception){
                addFail.value = e.message
                Log.i("ssss", "addCar: wdefrgthyujkl")
            }
        }
    }
}